import React, { Component } from "react";

import PageTitle from "components/page-title/index.jsx";

import Mutil from "util/mim.jsx";
import Product from "server/product-server.jsx";
import CategorySelector from "./category-selector.jsx";
import FileUploader from "util/file-uploader/index.jsx";
import "./save.scss";
import RichEditor from "util/rich-editor/index.jsx";
const product = new Product();
const mm = new Mutil();
class ProductSave extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: this.props.match.params.pid,
      name: "",
      subtitle: "",
      categoryId: 0,
      parentCategoryId: 0,
      subImages: [],
      price: "",
      stock: "",
      detail: "",
      status: 1 //状态1在售
    };
  }
  componentDidMount() {
    this.loadProduct();
  }
  // 加载商品详情
  loadProduct() {
    // 有id的时候，表示编辑功能，需要表单回填
    if (this.state.id) {
      product.getProduct(this.state.id).then(
        res => {
          let images = res.subImages.split(",");
          res.subImages = images.map(imgUri => {
            return {
              uri: imgUri,
              url: res.imageHost + imgUri
            };
          });
          res.defaultDetail = res.detail;
          this.setState(res);
        },
        errMsg => {
          mm.errorTips(errMsg);
        }
      );
    }
  }
  //简单字段改变
  onValueChange(e) {
    let name = e.target.name;
    let value = e.target.value.trim();
    this.setState({
      [name]: value
    });
  }
  // 品类选择
  onCategoryChange(categoryId, parentCategoryId) {
    this.setState({
      categoryId: categoryId,
      parentCategoryId: parentCategoryId
    });
    // console.log('一级',categoryId)
    // console.log('二级',parentCategoryId)
  }
  //上传图片成功
  onUploadSuccess(res) {
    let subImages = this.state.subImages;
    subImages.push(res);
    this.setState({
      subImages: subImages
    });
  }

  //上传图片失败
  onUploadError(errMsg) {
    mm.errorTips(errMsg);
  }
  //删除图片
  onImageDelete(e) {
    // let index = e.target.index;
    let index = parseInt(e.target.getAttribute("index"));
    let subImages = this.state.subImages;
    subImages.splice(index, 1);
    this.setState({
      subImages: subImages
    });
  }
  //富文本编辑器
  onDetailValueChange(value) {
    console.log(value);
    this.setState({
      detail: value
    });
  }
  getSubImagesString() {
    return this.state.subImages.map(image => image.uri).join(",");
  }
  //提交表单
  onSubmit() {
    let products = {
      name: this.state.name,
      subtitle: this.state.subtitle,
      categoryId: parseInt(this.state.categoryId),
      subImages: this.getSubImagesString(),
      detail: this.state.detail,
      price: parseFloat(this.state.price),
      stock: parseInt(this.state.stock),
      status: this.state.status
    };
    let productCheckResult = product.checkProduct(products);
    if (this.state.id) {
      product.id = this.state.id;
    }
    // 表单验证成功
    if (productCheckResult.status) {
      product.saveProduct(products).then(
        res => {
          mm.successTips(res);
          this.props.history.push("/product/index");
        },
        errMsg => {
          mm.errorTips(errMsg);
        }
      );
    }
    // 表单验证失败
    else {
      mm.errorTips(productCheckResult.msg);
    }
  }
  render() {
    return (
      <div id="page-wrapper">
        <PageTitle title={this.state.id ? "编辑商品" : "添加商品"} />
        <div className="form-horizontal">
          <div className="form-group">
            <label for="inputEmail3" className="col-md-2 control-label">
              商品名称
            </label>
            <div className="col-md-5">
              <input
                type="email"
                className="form-control"
                placeholder="请输入商品名称"
                name="name"
                onChange={e => this.onValueChange(e)}
                value={this.state.name}
              />
            </div>
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              商品描述
            </label>
            <div className="col-md-5">
              <input
                type="test"
                className="form-control"
                placeholder="Password"
                name="subtitle"
                onChange={e => this.onValueChange(e)}
                value={this.state.subtitle}
              />
            </div>
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              所属分类
            </label>
            <CategorySelector
              categoryId={this.state.categoryId}
              parentCategoryId={this.state.parentCategoryId}
              onCategoryChange={(categoryId,parentCategoryId) =>
                this.onCategoryChange(categoryId,parentCategoryId)
              }
            />
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              商品价格
            </label>
            <div className="col-md-3">
              <div className="input-group">
                <input
                  type="number"
                  className="form-control"
                  placeholder="Password"
                  name="price"
                  onChange={e => this.onValueChange(e)}
                  value={this.state.price}
                />
                <span className="input-group-addon">元</span>
              </div>
            </div>
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              商品库存
            </label>
            <div className="col-md-3">
              <div className="input-group">
                <input
                  type="number"
                  className="form-control"
                  placeholder="Password"
                  name="stock"
                  onChange={e => this.onValueChange(e)}
                  value={this.state.stock}
                />
                <span className="input-group-addon">个</span>
              </div>
            </div>
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              商品图片
            </label>
            <div className="col-md-10">
              {this.state.subImages.length ? (
                this.state.subImages.map((image, index) => (
                  <div className="img-icon" key={index}>
                    <img src={image.url} alt="image" className="img" />
                    <i
                      className="fa fa-close"
                      index={index}
                      onClick={e => this.onImageDelete(e)}
                    />
                  </div>
                ))
              ) : (
                <div>请上传图片</div>
              )}
            </div>
            <div className="col-md-10 col-md-offset-2 file-upload-con">
              <FileUploader
                onSuccess={res => this.onUploadSuccess(res)}
                onError={errMsg => this.onUploadError(errMsg)}
              />
            </div>
          </div>
          <div className="form-group">
            <label for="inputPassword3" className="col-md-2 control-label">
              商品详情
            </label>
            <div className="col-md-10">
              <RichEditor
                detail={this.state.detail}
                defaultDetail={this.state.defaultDetail}
                onValueChange={value => this.onDetailValueChange(value)}
              />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-offset-2 col-sm-10">
              <button
                type="submit"
                className="btn btn-primary"
                onClick={e => {
                  this.onSubmit(e);
                }}
              >
                提交
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default ProductSave;
